<template>
	<view>
		<!-- 自定义头部导航栏 -->
		<nav-bar>
			<!-- 未选中插槽 -->
			<template v-if="checkedCount === 0">
				<template slot="left">
					<view
						style="width:60rpx;height:60rpx;"
						class="bg-light flex align-center justify-center ml-3 rounded-circle"
						@click="backUp"
						v-show="current"
					>
						<text class="iconfont icon-fanhui"></text>
					</view>
					<text slot="left" class="ml-3 font-md">
						{{ current ? current.name : '首页' }}
					</text>
				</template>

				<template slot="right">
					<view
						style="width:60rpx;height:60rpx;"
						class="bg-light flex align-center justify-center mr-3 rounded-circle"
						@click="openAddDialog"
					>
						<text class="iconfont icon-zengjia"></text>
					</view>
					<view
						style="width:60rpx;height:60rpx;"
						class="bg-light flex align-center justify-center mr-3 rounded-circle"
						@click="handleOther"
					>
						<text class="iconfont icon-gengduo"></text>
					</view>
				</template>
			</template>
			<!-- 选中插槽 -->
			<template v-else>
				<text slot="left" class="font-md text-primary ml-3" @click="handleCheckAll(false)">
					取消
				</text>
				<text slot="center" class="font-md font-weight-bold">
					已选中{{ checkedCount }}个
				</text>
				<view slot="right" class="font-md mr-3 text-primary" @click="handleCheckAll(true)">
					全选
				</view>
			</template>
		</nav-bar>
		<!-- 搜索框 -->
		<view class="px-3 py-2">
			<view class="position-relative">
				<!-- 搜索图标 -->
				<view
					style="height: 70rpx;width:70rpx;position:absolute;top:0;left:0;"
					class="flex align-center justify-center text-light-muted"
				>
					<text class="iconfont icon-sousuo"></text>
				</view>
				<input
					class="bg-light rounded-circle font-md"
					style="height:70rpx;padding-left:70rpx;"
					type="text"
					placeholder="搜索网盘文件 . . ."
					@input="searchHandler"
				/>
			</view>
		</view>
		<!-- 列表组件 -->
		<f-list
			v-for="(item, index) in list"
			:key="index"
			:item="item"
			:index="index"
			@select="emitSelect"
			@click="doEvent(item)"
		></f-list>
		<!-- 底部组件 -->
		<view v-if="checkedCount">
			<!-- 浮动占位 -->
			<view style="height: 115rpx;"></view>
			<view
				style="height: 115rpx;bottom: 100rpx;"
				class="bg-primary text-white flex align-stretch fixed-bottom"
			>
				<view
					v-for="item in actions"
					:key="item.icon"
					class="flex-1 flex align-center justify-center flex-column"
					style="line-height:1.5;"
					hover-class="bg-hover-primary"
					@click="handleBottomEvent(item)"
				>
					<text class="iconfont" :class="item.icon"></text>
					<text>{{ item.name }}</text>
				</view>
			</view>
		</view>
		<!-- 删除 -->
		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog
				type="error"
				cancelText="取消"
				confirmText="确定"
				title="删除确认"
				content="您确定要删除该文件吗?"
				@confirm="dialogConfirm"
				@close="dialogClose"
			></uni-popup-dialog>
		</uni-popup>
		<!-- 重命名 -->
		<uni-popup ref="popupChong">
			<uni-popup-dialog
				ref="inputClose"
				mode="input"
				title="重命名"
				:value="renameVal"
				placeholder="请输入内容..."
				@confirm="dialogInputConfirm"
			></uni-popup-dialog>
		</uni-popup>
		<!-- 增加按钮 -->
		<!-- 分享示例 -->
		<uni-popup ref="share" type="share" safeArea backgroundColor="#fff">
			<uni-popup-share :bottomData="bottomData" @select="handleAddSelect"></uni-popup-share>
		</uni-popup>
		<!-- 新建文件夹 -->
		<uni-popup ref="addDirPopupRef">
			<uni-popup-dialog
				ref="addDirRef"
				mode="input"
				title="新建文件夹"
				:value="dirname"
				placeholder="请输入内容..."
				@confirm="addDirInputConfirm"
			></uni-popup-dialog>
		</uni-popup>
		<!-- 更多 -->
		<uni-popup ref="otherPopupRef" class="position-relative">
			<view
				class="bg-white position-fixed border-top flex flex-column align-center justify-center"
				style="width: 750rpx;height: 200rpx;bottom: 0rpx;left:0rpx;"
			>
				<view
					v-for="(item, index) in sortList"
					:key="item.key"
					class="flex-1 flex align-center justify-center border-bottom"
					:class="{ 'text-primary': sortIndex === index }"
					style="width: 100%;"
					hover-class="bg-hover-light"
					@click="changeSort(index)"
				>
					{{ item.name }}
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import navBar from '@/components/common/nav-bar.vue'
import fList from '@/components/common/f-list.vue'

export default {
	components: {
		navBar,
		fList
	},
	data() {
		return {
			sortIndex: 0,
			sortList: [
				{
					name: '名称排序',
					key: 'name'
				},
				{
					name: '时间排序',
					key: 'created_time'
				}
			],
			dirname: '',
			bottomData: [
				{
					text: '上传图片',
					type: 'icon',
					icon: 'icon-file-b-6 text-success',
					name: 'image'
				},
				{
					text: '上传视频',
					type: 'icon',
					icon: 'icon-file-b-9 text-primary',
					name: 'video'
				},
				{
					text: '上传文件',
					type: 'icon',
					icon: 'icon-file-b-8 text-muted',
					name: 'none'
				},
				{
					text: '新建文件夹',
					type: 'icon',
					icon: 'icon-file-b-2 text-warning',
					name: 'dir'
				}
			],
			renameVal: '',
			list: [],
			dirs: []
		}
	},
	onLoad() {
		const dirs = uni.getStorageSync('dirs')
		if (dirs) {
			this.dirs = JSON.parse(dirs)
		}
		this.getData()
		uni.$on('updateData', () => {
			uni.showToast({
				title: '保存成功',
				icon: 'none'
			})
			this.getData()
		})
	},
	computed: {
		checkList() {
			return this.list.filter(item => item.checked)
		},
		checkedCount() {
			return this.checkList.length
		},
		getFileID() {
			let len = this.dirs.length
			if (len === 0) {
				return 0
			}
			return this.dirs[len - 1].id
		},
		current() {
			let len = this.dirs.length
			if (len === 0) {
				return false
			}
			return this.dirs[len - 1]
		},
		actions() {
			if (this.checkedCount > 1) {
				return [
					{
						icon: 'icon-xiazai',
						name: '下载'
					},
					{
						icon: 'icon-shanchu',
						name: '删除'
					}
				]
			}
			return [
				{
					icon: 'icon-xiazai',
					name: '下载'
				},
				{
					icon: 'icon-fenxiang-1',
					name: '分享'
				},
				{
					icon: 'icon-shanchu',
					name: '删除'
				},
				{
					icon: 'icon-chongmingming',
					name: '重命名'
				}
			]
		}
	},
	methods: {
		formaList(list) {
			return list.map(item => {
				let type = 'none'
				if (item.isdir == 1) {
					type = 'dir'
				} else {
					type = item.ext.split('/')[0] || 'none'
				}
				return {
					type,
					checked: false,
					...item
				}
			})
		},
		getData() {
			let orderby = this.sortList[this.sortIndex]
			this.$H
				.get(`/file?file_id=${this.getFileID}&orderby=${orderby.key}`, {
					token: true
				})
				.then(res => {
					this.list = this.formaList(res)
				})
		},
		backUp() {
			this.dirs.pop()
			this.getData()
			uni.setStorageSync('dirs', JSON.stringify(this.dirs))
		},
		emitSelect(data) {
			const { index, value } = data
			this.list[index].checked = value
		},
		// 全选 && 取消
		handleCheckAll(check) {
			this.list.forEach(item => (item.checked = check))
		},
		// 多选事件
		handleBottomEvent(item) {
			switch (item.name) {
				case '删除':
					this.$refs.alertDialog.open()
					break
				case '重命名':
					this.renameVal = this.checkList[0].name
					this.$refs.popupChong.open()
					break
				case '下载':
					this.download()
					break
				case '分享':
					this.share()
					break
			}
		},
		// 分享
		share() {
			this.$H
				.post('/share/create', { file_id: this.checkList[0].id }, { token: true })
				.then(res => {
					uni.showModal({
						content: res,
						showCancel: false,
						success: () => {
							uni.setClipboardData({
								data: res,
								success: () => {
									this.handleCheckAll(false)
									uni.showToast({
										title: '复制成功',
										icon: 'none'
									})
								}
							})
						}
					})
				})
		},
		// 下载
		download() {
			this.checkList.forEach(item => {
				if (item.isdir === 0) {
					const key = this.getId(8)
					// 不是文件夹
					let obj = {
						name: item.name,
						type: item.type,
						size: item.size,
						key,
						progress: 0,
						status: true,
						created_time: new Date().getTime()
					}
					this.$store.dispatch('createDownloadList', obj)
					const url = item.url

					const d = uni.downloadFile({
						url,
						success: res => {
							if (res.statusCode === 200) {
								// 下载成功  移动保存,不支持H5
								// #ifdef H5
								uni.saveFile({
									tempFilePath: item.tempFilePath
								})
								// #endif
							}
						}
					})
					// 监听进度条
					d.onProgressUpdate(p => {
						this.$store.dispatch('updateDownloadList', {
							progress: p.progress,
							key,
							status: true
						})
					})
				}
			})
			uni.showToast({
				title: '已加入下载任务',
				icon: 'none'
			})
			this.handleCheckAll(false)
		},
		// 重命名
		dialogInputConfirm(val) {
			if (val == '' || !val) {
				return
			}
			this.renameVal = val
			this.$H
				.post(
					'/file/rename',
					{
						id: this.checkList[0].id,
						name: this.renameVal
					},
					{ token: true }
				)
				.then(res => {
					uni.showToast({
						title: '重命名成功',
						icon: 'none'
					})
					this.renameVal = ''
					this.$refs.popupChong.close()
					this.handleCheckAll(false)
					this.getData()
				})
		},
		//  删除文件夹
		dialogConfirm() {
			let ids = this.checkList.map(item => item.id)
			this.$H.post('/file/delete', { ids: ids.join(',') }, { token: true }).then(res => {
				uni.showToast({
					title: '删除成功',
					icon: 'none'
				})
				this.$refs.alertDialog.close()
				this.getData()
			})
		},
		dialogClose() {},
		// 上传按钮
		openAddDialog() {
			this.$refs.share.open()
		},
		getId(length) {
			return Number(
				Math.random()
					.toString()
					.substr(3, length) + Date.now()
			).toString(36)
		},
		upload(file, type) {
			const key = this.getId(8)
			let name = file.name
			if (!name) {
				name = file.path.substring(file.path.lastIndexOf('/') + 1)
			}
			let obj = {
				name,
				type,
				size: file.size,
				key,
				progress: 0,
				status: true,
				created_time: new Date().getTime()
			}
			this.$store.dispatch('createUploadJob', obj)
			this.$H
				.upload(
					'/upload?file_id=' + this.getFileID,
					{
						filePath: file.path
					},
					p => {
						this.$store.dispatch('updateUploadJob', {
							status: true,
							progress: p,
							key
						})
					}
				)
				.then(res => {
					// 上传成功
					this.getData()
				})
		},
		// 上传弹窗选择按钮
		handleAddSelect(data) {
			const { item, index } = data
			switch (item.name) {
				case 'image':
					// 上传图片
					uni.chooseImage({
						count: 9,
						success: res => {
							res.tempFiles.forEach(item => {
								this.upload(item, 'image')
							})
						}
					})
					break
				case 'viedo':
					// 上传视频
					uni.chooseVideo({
						count: 1,
						success: res => {
							let name = ''
							let size = 0
							// #ifndef H5
							name = res.tempFilePath.substring(res.tempFilePath.lastIndexOf('/') + 1)
							size = res.size
							// #endif
							this.upload({
								path: res.tempFilePath,
								name,
								type: 'video',
								size
							})
						}
					})
					break
				case 'none':
					// 上传文件
					uni.chooseFile({
						count: 9,
						success: res => {
							res.tempFiles.forEach(item => {
								this.upload(item, 'none')
							})
						}
					})
					break
				case 'dir':
					// 新建文件夹
					this.dirname = '新建文件夹'
					this.$refs.addDirPopupRef.open()
					break
			}
		},
		// 新建文件夹
		addDirInputConfirm(val) {
			if (val == '') {
				uni.showToast({
					title: '文件夹名称不能为空',
					icon: 'none'
				})
				return
			}
			this.dirname = val

			this.$H
				.post(
					'/file/createDir',
					{
						file_id: this.getFileID,
						name: this.dirname
					},
					{ token: true }
				)
				.then(res => {
					uni.showToast({
						title: '新建成功',
						icon: 'none'
					})
					this.$refs.addDirPopupRef.close()
					this.getData()
				})
		},
		// 列表选择事件
		doEvent(item) {
			switch (item.type) {
				case 'image': // 预览图片
					let images = this.list.filter(item => item.type === 'image')
					uni.previewImage({
						current: item.url,
						urls: images.map(i => i.url)
					})
					break
				case 'video': // 预览视频
					uni.navigateTo({
						url: '../video/video?url=' + item.url + '&title=' + item.name
					})
					break
				default:
					this.dirs.push({ id: item.id, name: item.name })
					this.getData()
					uni.setStorage({
						key: 'dirs',
						data: JSON.stringify(this.dirs)
					})
					break
			}
		},
		// 更多按钮
		handleOther() {
			this.$refs.otherPopupRef.open()
		},
		// 切换排序
		changeSort(index) {
			this.sortIndex = index
			this.getData()
			this.$refs.otherPopupRef.close()
		},
		// 搜索
		searchHandler(e) {
			if (e.target.value == '') {
				this.getData()
				return
			}
			this.$H.get(`/file/search?keyword=${e.target.value}`, { token: true }).then(res => {
				this.list = this.formaList(res)
			})
		}
	}
}
</script>

<style></style>
